/**
 * ----------------------------------------------------------------------------
 * Copyright Jens Konopka
 * 
 * Alle Rechte vorbehalten.
 * Licence: Apache 2.0
 * ----------------------------------------------------------------------------
 *
 * created on 03.01.2012 by jkonopka
 */
package org.knoppers.examples;

import java.util.HashMap;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

/**
 * @author jkonopka
 * 
 */
public class Main {

	EntityManagerFactory emf;

	public static void main(String[] args) {
		new Main().test();
	}

	void test() {
		Map<Object, Object> map = new HashMap<Object, Object>();
		emf = Persistence.createEntityManagerFactory("MeineJpaPU", map);
		try {
			MeineDaten dat = new MeineDaten();
			dat.setMeinText("Hallo Welt");

			createEntity(dat);
			Object id = dat.getId();

			System.out.println("\n--- " + readEntity(MeineDaten.class, id)
					+ " ---\n");
		} finally {
			emf.close();
		}
	}

	public <T> void createEntity(T entity) {
		EntityManager em = emf.createEntityManager();
		EntityTransaction tx = em.getTransaction();
		try {
			tx.begin();
			em.persist(entity);
			tx.commit();
		} catch (RuntimeException ex) {
			if (tx != null && tx.isActive())
				tx.rollback();
			throw ex;
		} finally {
			em.close();
		}
	}

	public <T> T readEntity(Class<T> clss, Object id) {
		EntityManager em = emf.createEntityManager();
		try {
			return em.find(clss, id);
		} finally {
			em.close();
		}
	}
}
